#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "dSFMT.h"

static int max(int a, int b)
{
    if (a > b)
        return a;

    return b;
}


int main(int argc, char **argv)
{
    fprintf(stderr, "PseudoGen: %s\n", dsfmt_get_idstring());

    unsigned int seed;
    FILE *f;
    f = fopen("/dev/random", "r");
    fread(&seed, 1, sizeof(int), f);
    fclose(f);
    fprintf(stderr, "Seed is: %u (%d bit)\n", seed, (int)sizeof(seed)*8);

    dsfmt_t gen;
    dsfmt_init_gen_rand(&gen, seed);

    int dataSize = (max(dsfmt_get_min_array_size(), 1024*1024) / sizeof(double) + 1)*sizeof(double);
    double *data = (double*)malloc(dataSize);
    int len = dataSize / sizeof(double);
    while (len % 2 != 0)
        len++;
    dataSize = len * sizeof(double);

    fprintf(stderr, "Chunk Size %d\n", dataSize);
    fprintf(stderr, "Chunk as Vector of Doubles %d\n", len);

    FILE *fout = stdout;
    if (argc > 1)
    {
        fprintf(stderr, "Opening Output File: %s \n", argv[1]);
        fout = fopen(argv[1], "w+");
        if  (fout == NULL)
        {
            fprintf(stderr, "Unable to open output file\n");
            return -1;
        }
    }
    else
    {
        fprintf(stderr, "Output File is: stdout \n");
    }

    int chunksSoFar = 0;
    while (1)
    {
        dsfmt_fill_array_close_open(&gen, data, len);
        size_t written = fwrite(data, 1, dataSize, fout);
        if (written < dataSize)
        {
            fprintf(stderr, "Error: unable to write %ld < %d \n", written, dataSize);
            break;
        }
        chunksSoFar++;
    }

    if (fout != stdout)
    {
        fclose(fout);
    }

    fprintf(stderr, "Chunks Written: %d\n", chunksSoFar);

    return 0;
}
